package com.example.usermanagement.controller;

import com.example.usermanagement.entity.User;
import com.example.usermanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam("email") String email,
                               @RequestParam(value = "role", defaultValue = "USER") String role,
                               @RequestParam(value = "avatar", required = false) MultipartFile avatar,
                               RedirectAttributes redirectAttributes) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password); // 明文密码
            user.setEmail(email);
            user.setRole(role);

            // 处理头像上传
            if (avatar != null && !avatar.isEmpty()) {
                // 定义上传目录
                String uploadDir = "src/main/resources/static/uploads/avatars/";
                Path uploadPath = Paths.get(uploadDir);

                // 创建目录如果不存在
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 生成唯一文件名
                String fileName = UUID.randomUUID().toString() + "-" + avatar.getOriginalFilename();
                Path filePath = uploadPath.resolve(fileName);

                // 保存文件
                Files.copy(avatar.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

                // 保存文件路径到用户对象
                user.setAvatarPath("/uploads/avatars/" + fileName);
            }

            userService.registerUser(user);
            redirectAttributes.addFlashAttribute("message", "注册成功，请登录");
            return "redirect:/login";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "注册失败: " + e.getMessage());
            e.printStackTrace();
            return "redirect:/register";
        }
    }


    @GetMapping("/login")
    public String showLoginForm(@RequestParam(value = "error", required = false) String error,
                                Model model) {
        if (error != null) {
            model.addAttribute("error", true);
        }
        return "login";
    }
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        RedirectAttributes redirectAttributes) {
        Optional<User> userOptional = userService.loginUser(username, password);
        if (userOptional.isPresent()) {
            // 登录成功，重定向到用户列表页面
            return "redirect:/users";
        } else {
            // 登录失败，添加错误信息并重定向回登录页面
            redirectAttributes.addFlashAttribute("error", "Invalid username or password");
            return "redirect:/login?error=true";
        }
    }

    @GetMapping("/users")
    public String showUsers(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "users";
    }

    // 显示编辑用户页面
    @GetMapping("/users/edit/{id}")
    public String showEditUserForm(@PathVariable Long id, Model model) {
        User user = userService.getUserById(id).orElse(new User());
        model.addAttribute("user", user);
        return "edit";
    }

    // 更新用户信息（包含头像上传）
    @PostMapping("/users/update")
    public String updateUser(@ModelAttribute("user") User user,
                             @RequestParam(value = "avatar", required = false) MultipartFile avatar,
                             RedirectAttributes redirectAttributes) {
        try {
            // 处理头像上传
            if (avatar != null && !avatar.isEmpty()) {
                // 定义上传目录（使用绝对路径）
                String uploadDir = "src/main/resources/static/uploads/avatars/";
                Path uploadPath = Paths.get(uploadDir);

                // 创建目录如果不存在
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 生成唯一文件名
                String fileName = UUID.randomUUID().toString() + "-" + avatar.getOriginalFilename();
                Path filePath = uploadPath.resolve(fileName);

                // 保存文件
                Files.copy(avatar.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

                // 保存文件路径到用户对象（相对路径用于访问）
                user.setAvatarPath("/uploads/avatars/" + fileName);
            }

            userService.updateUser(user);
            redirectAttributes.addFlashAttribute("message", "用户更新成功");
        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("error", "头像上传失败: " + e.getMessage());
            e.printStackTrace();
            return "redirect:/users"; // 即使出错也要返回重定向
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败: " + e.getMessage());
            e.printStackTrace();
            return "redirect:/users";
        }

        return "redirect:/users";
    }


    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return "redirect:/users";
    }
}
